
import re
import sys
import string
import glob
import pepe.p_txt.bigtxt as bt

n = '\x0D\x0A'

#print [10]*3
def main(inpfmask, span=10, lr='right'):
    ''' '''
    
    for f in glob.glob(inpfmask):
        print f
        o = open(f + '_spanned.#', 'wb')
        spans = None; lino = 0; span = int(span)
        #print span
    
        cols = string.split(open(f, 'rb').readline(), '\t')
        spans = [0] * len(cols)    
        # finding out columns span
        for line in bt.lines(f):
            lino += 1
            line = re.sub(n, '', line)
            cols = string.split(line, '\t')
            for i, v in enumerate(cols):
                if len(v) > spans[i]: spans[i] = len(v)
    
        # processing lines
        for line in bt.lines(f):  
            line = re.sub(n, '', line)
            cols = string.split(line, '\t')
            for i,v in enumerate(cols):
                # col_max_len + span - current_len
                curr_span = spans[i] + span - len(v)
                if lr == 'left':
                    o.write(v + ' ' * curr_span)
                else:
                    o.write(' ' * curr_span + v)
            o.write(n)
    
        o.close()

if __name__ == "__main__":
    ''' '''
    #main('new.txt')
    #print sys.argv
    if  len(sys.argv) == 2:
        main(sys.argv[1])
    elif  len(sys.argv) == 3:
        main(sys.argv[1], sys.argv[2])
    elif  len(sys.argv) == 4:
        main(sys.argv[1], sys.argv[2], sys.argv[3])
    else:
        print '''
        
        Transforming tab separated values to spanned text.
        
        spanned.py <span above max> <left|right>
        
        <span above max> how much additional space (span) should be added
                         default is 10 (spaces more than widest value in column)

        <left|right>     whether to be spanned from left or right
                         default (if not defined) is right
        '''
